//
//  WZTabbarView.m
//  ETong
//
//  Created by wanzhao on 15/10/28.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZTabbarView.h"
#import "WZTabBarButton.h"


@interface WZTabbarView ()

@property (nonatomic, strong) WZTabBarButton *selectedBtn;

@end


@implementation WZTabbarView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = WhiteColor;
    }
    return self;
}

- (void)addButtonWithItem:(UITabBarItem *)item
{
    WZTabBarButton *button = [WZTabBarButton buttonWithType:UIButtonTypeCustom];
    button.item = item;
    
    [button setImage:item.finishedUnselectedImage forState:UIControlStateNormal];
    [button setImage:item.finishedSelectedImage forState:UIControlStateSelected];
//    [button setTitle:item.title forState:UIControlStateNormal];
//    [button setTitle:item.title forState:UIControlStateSelected];
//    [button setTitleColor:RGBCOLOR(47, 147, 231) forState:UIControlStateSelected];
//    [button setTitleColor:RGBCOLOR(176, 176, 176) forState:UIControlStateNormal];
//    button.titleLabel.font = Font14;
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
    button.tag = self.subviews.count;
    [self addSubview:button];
    if (self.subviews.count == 1) {
        [self buttonClicked:button];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    int i = 0;
    CGFloat btnY = 3;
    CGFloat btnW = self.width / self.subviews.count;
    CGFloat btnH = self.height - 3;
    CGFloat btnX = 0;
    for (UIButton *btn in self.subviews) {
        btnX = i * btnW;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        i ++;
    }
}
- (void)buttonClicked:(WZTabBarButton *)button
{
    if (button == self.selectedBtn) {
        return;
    }
    
    self.selectedBtn.selected = NO;
    button.selected = YES;
    self.selectedBtn = button;
    if ([self.delegate respondsToSelector:@selector(tabBarViewSelectControllerFromIndex:toIndex:)]) {
        [self.delegate tabBarViewSelectControllerFromIndex:self.selectedBtn.tag toIndex:button.tag];
    }
}


@end
